package com.dashuai.modbus.config;

import com.dashuai.modbus.core.master.ModbusTCPMaster;
import com.dashuai.modbus.util.CheckUtil;
import com.serotonin.modbus4j.exception.ModbusInitException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author QM
 * @date 2023/7/28
 */
@EnableConfigurationProperties(TCPMasterProperties.class)
@AutoConfigureOrder
@Slf4j
public class TCPMasterAutoConfiguration {
    // TODO AutoConfigureOrder 这个注解存疑，控制Bean初始化顺序的注解

    @Autowired
    private TCPMasterProperties tcpMasterProperties;


    @Bean
    public ModbusTCPMaster modbusTCPMaster() throws ModbusInitException {

        final List<String> ips = tcpMasterProperties.getIps();
        final List<Integer> ports = tcpMasterProperties.getPorts();
        final String defaultIp = tcpMasterProperties.getDefaultIp();
        final int defaultPort = tcpMasterProperties.getDefaultPort();

        checkTCPMasterParameter(defaultIp, defaultPort, ips, ports);

        return new ModbusTCPMaster(defaultIp, defaultPort, ips, ports);
    }

    private void checkTCPMasterParameter(String defaultIp, int defaultPort, List<String> ips, List<Integer> ports) throws ModbusInitException {

        CheckUtil.checkIPAndPort(defaultIp, defaultPort);

        if (ips.size() != ports.size()) {
            log.error("The tcp ip address and port number must be the same");
            throw new ModbusInitException("The tcp ip address and port number must be the same");
        }

        for (int i = 0; i < ips.size(); i++) {
            final String ip = ips.get(i);
            final Integer port = ports.get(i);
            CheckUtil.checkIPAndPort(ip, port);
        }

        if (ips.isEmpty()) {
            log.warn("The number of tcp master ip addresses is 0, which can be ignored if there is no demand");
        }
    }
    // TODO ModbusTCPMaster，正在做，待完善的有：ModbusTCPSlave、ModbusRTUMaster、ModbusRTUSlave
}
